<!DOCTYPE html>
<html lang='en'>

<head>
    <meta charset='UTF-8'>
    <meta name='viewport' content='width=device-width, initial-scale=1.0'>
    <meta http-equiv='X-UA-Compatible' content='ie=edge'>
    <title>操作表格</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        table {
            /*  border:1px solid red; */
            border-collapse: collapse;
            text-align: center;
            width: 500px;
            border-spacing: 2px;
        }

        th,
        td {
            border: 1px solid red;
            width: 100px;
            height: 24px;
            margin: 10px;

        }

        tr>td:nth-child(3) {
            text-decoration: line-through;
        }

        thead,
        tbody {
            display: block;
            width: 700px;
            display: flex;
            justify-content: space-between;
            flex-direction: column;
        }

        tr>td:nth-child(6) {
            cursor: pointer;
        }

        section {
            width: 700px;
            margin: 0 auto;
        }

        input,
        select {
            margin-top: 10px;
        }

        #bnt {
            margin: 10px 0;
        }
    </style>
</head>

<body>
    <section>
        商品名称:
        <input type="text" class='name'>
        <br> 商品类别:
        <select name="food">
            <option>优选水果</option>
            <option>卤味熟食</option>
            <option>饮料酒水</option>
            <option>休闲零食</option>
        </select>
        <br> 商品原价:
        <input type="text" class='prevPrice'>
        <br> 商品现价:
        <input type="text" class='nowPrice'>
        <br> 商品数量:
        <input type="text" class='num'>
        <br> 是否标红:
        <input type='radio' class='yRadio'>&nbsp;是&nbsp;&nbsp;
        <input type='radio' class='nRadio'>&nbsp;否
        <br>
        <button id='bnt'>提交信息</button>
        <hr style='margin-bottom:5px;'>
        <a href="javascript:;" class='checkAll'>全部</a>
        <a href="javascript:;" class='fruit'>优选水果</a>
        <a href="javascript:;" class='meat'>卤味熟食</a>
        <a href="javascript:;" class='water'>饮料酒水</a>
        <a href="javascript:;" class='snake'>休闲零食</a>
        <hr style='margin:5px 0;'>
        <table>
            <thead>
                <th>商品名称</th>
                <th>商品类别</th>
                <th>原价</th>
                <th>现价</th>
                <th>库存</th>
                <th>是否标红</th>
                <th>删除</th>
            </thead>
            <tbody>

            </tbody>
        </table>
    </section>
</body>
<html>
<script src="jQuery/jquery-3.6.0.js"></script>
<script>
    /*
        实现动态添加表格，且实现删除
        1.先写基本结构，加css样式
        2.写js动态实现
    */

    //获取dom结构
    let name = document.querySelector('.name')
    let food = document.querySelector("[name='food']")
    let prev = document.querySelector('.prevPrice')
    let now = document.querySelector('.nowPrice')
    let num = document.querySelector('.num')
    let bnt = document.querySelector('#bnt')
    let opts = document.querySelectorAll('option')
    let tbody = document.querySelector('tbody')
    let yRadio = document.querySelector('.yRadio')
    let nRadio = document.querySelector('.nRadio')

    let str = '';
    //给提交信息按钮绑定单击事件

    bnt.onclick = function () {
        //接收单选框的状态布尔值
        let selected;
        if ($('.yRadio').prop('checked') == true && $('.nRadio').prop('checked') == false) {
            selected = true;
            // $('.firstTd').css('color', 'red');
        } else {
            selected = false;
        }
        //判断所有输入框都不为空
        if (name.value == '' || prev == '' || now.value == '' || num.value == '' || $('.yRadio').prop('checked') == false && $('.nRadio').prop('checked') == false) {
            alert('表格各项不能为空')//
            return;
        }
        //到这里说明没有空的表单,正则判断商品只能是中文汉字
        let reg1 = /[^\u4E00-\u9FA5]/g;
        if (reg1.test(name.value)) {
            alert('商品名称必须是汉字');
            return;
        }
        //判断价格、数量只能是数字
        let reg2 = /^\d{1,5}$/
        if (!reg2.test(prev.value) || !reg2.test(now.value) || !reg2.test(num.value)) {
            alert('原价、现价、数量必须是数字');
            return;
        }
        //到这里说明基本的填写没问题，实现动态添加表格，将数据添加到表格中去，同时存储到localStorage里面
        //当都填入正确信息后，才能提交   
        let localData = localStorage.getItem('data');
        // 判断购物车是否为空
        if (!localData) {// 购物车为空
            // 直接将此次购买的商品信息写入本地
            let obj = {
                name: name.value,
                food: food.value,
                prev: prev.value,
                now: now.value,
                num: num.value,
                selected: selected,
            };
            // 存入localStorage
            localStorage.setItem('data', JSON.stringify([obj]));
        } else {
            let data = JSON.parse(localData);
            // 判断之前该用户知否将这个商品加入过本地
            let res = data.findIndex(v => v.name == name.value && v.food == food.value);
            if (res != -1) { // 如果res不为-1则  这个用户之前就已经将这个商品加入本地
                // 将这个之前就加入到本地的数据拿出来
                let cart = data.find(v => v.name == name.value && v.food == food.value);
                cart.num = parseInt(cart.num) + parseInt(num.value); // 将需要加入本地的商品数累加并入data数据中
                localStorage.setItem('data', JSON.stringify(data));
            } else { // 这个用户之前没有将这个商品加入过本地
                data.push({
                    name: name.value,
                    food: food.value,
                    prev: prev.value,
                    now: now.value,
                    num: num.value,
                    selected: selected,
                });
                localStorage.setItem('data', JSON.stringify(data));
            }
        }

        //清空输入框
        name.value = ''
        prev.value = ''
        now.value = ''
        num.value = ''
        location.reload();
    }


    //动态渲染
    for (let i = 0; i < JSON.parse(localStorage.getItem('data')).length; i++) {
        if (JSON.parse(localStorage.getItem('data'))[i]['selected'] == true) {
            str = `
            <tr class='firstTr'>
                        <td class='firstTd'>${JSON.parse(localStorage.getItem('data'))[i].name}</td>
                        <td class='goodsType'>${JSON.parse(localStorage.getItem('data'))[i].food}</td>
                        <td>${JSON.parse(localStorage.getItem('data'))[i].prev}</td>
                        <td>${JSON.parse(localStorage.getItem('data'))[i].now}</td>
                        <td>${JSON.parse(localStorage.getItem('data'))[i].num}</td>
                        <td class='color'>${JSON.parse(localStorage.getItem('data'))[i].selected}</td>
                        <td><a href='javascript:;' class='del'>删除</a></d>
            </tr>
        `
            tbody.innerHTML += str
            // $('.firstTd').css('color','red')
            let firstTds = document.querySelectorAll('.firstTd');
            firstTds[i].style.color = 'red'
            $('tbody').prepend($('.firstTr').last())
        }//插入到最前面
        else {
            str = `
            <tr class='firstTr'>
                        <td class='firstTd'>${JSON.parse(localStorage.getItem('data'))[i].name}</td>
                        <td class='goodsType'>${JSON.parse(localStorage.getItem('data'))[i].food}</td>
                        <td>${JSON.parse(localStorage.getItem('data'))[i].prev}</td>
                        <td>${JSON.parse(localStorage.getItem('data'))[i].now}</td>
                        <td>${JSON.parse(localStorage.getItem('data'))[i].num}</td>
                        <td class='color'>${JSON.parse(localStorage.getItem('data'))[i].selected}</td>
                        <td><a href='javascript:;' class='del'>删除</a></d>
            </tr>
        `
            tbody.innerHTML += str
            let firstTds = document.querySelectorAll('.firstTd');
            firstTds[i].style.color = '#000'
            $('tbody').prepend($('.firstTr').last())
        }
    }

    $('.del').on('click', function () {//当用户点击删除的时候，相应的要将本地数据删除
        for (let i = 0; i < JSON.parse(localStorage.getItem('data')).length; i++) {
            var arr = JSON.parse(localStorage.getItem('data'));
            if (JSON.parse(localStorage.getItem('data'))[i]['name'] === $(this).parent().siblings().eq(0).text()) {
                arr.splice(i, 1)
                $(this).parent().parent().remove();
            }
            localStorage.setItem('data', JSON.stringify(arr));
        }
        location.reload();
    }
    )
    //input单选事件
    $('input:radio').click(function () {
        var $radio = $(this);
        if ($radio.data('checked')) {
            $radio.prop('checked', false);
            $radio.data('checked', false);
        } else {
            $radio.prop('checked', true);
            $radio.data('checked', true);
        }
        // console.log($(this).prop('checked'))
    });
    //全选事件，显示全部,相同类至多两个
    $('.checkAll').click(function () {
        let firstTrs = document.querySelectorAll('.firstTr');
        $('.fruit').css('color', 'blue')
        $('.checkAll').css('color', 'red')
        $('.meat').css('color', 'blue')
        $('.water').css('color', 'blue')
        $('.snake').css('color', 'blue')
        // for(let i=0;i<JSON.parse(localStorage.getItem('data')).length;i++){
        //     for(let j=0;j<firstTrs.length;j++){
        //         let index =0;
        //         if(goodsType[i].innerText==goodsType[j].innerText){
        //             index++;
        //             if(index>2){
        //                 index=2
        //                 goodsType[i].innerText=goodsType[j].innerText
        //                 //goodsType[i].parentNode.style.display='none'
        //             }
        //         }
        //     }
        // }
        $('.goodsType').parent().siblings().css('display', 'block')
        $('.goodsType').parent().css('display', 'block')
    })
    //优选水果
    let goodsType = document.querySelectorAll('.goodsType')
    //console.log(goodsType)
    $('.fruit').click(function () {
        $('.fruit').css('color', 'red')
        $('.checkAll').css('color', 'blue')
        $('.meat').css('color', 'blue')
        $('.water').css('color', 'blue')
        $('.snake').css('color', 'blue')
        for (let i = 0; i < goodsType.length; i++) {
            if ($(this).text() == goodsType[i].innerText) {
                //console.log($(goodsType[i]))
                $(goodsType[i][i]).parent().siblings().css('display', 'none')
                $(goodsType[i]).parent().css('display', 'block')
            }
            else {
                $(goodsType[i]).parent().css('display', 'none')
            }

        }
        $('.firstTr:odd').css('background', '#ccc')
        $('.firstTr:even').css('background', 'pink')
    })
    //卤味熟食
    //let goodsType = document.querySelectorAll('.goodsType')
    $('.meat').click(function () {
        $('.fruit').css('color', 'blue')
        $('.checkAll').css('color', 'blue')
        $('.meat').css('color', 'red')
        $('.water').css('color', 'blue')
        $('.snake').css('color', 'blue')
        for (let i = 0; i < goodsType.length; i++) {
            if ($(this).text() == goodsType[i].innerText) {
                //console.log($(goodsType[i]))
                $(goodsType[i][i]).parent().siblings().css('display', 'none')
                $(goodsType[i]).parent().css('display', 'block')
            }
            else {
                $(goodsType[i]).parent().css('display', 'none')
            }
        }
    })

    //饮料
    //let goodsType = document.querySelectorAll('.goodsType')
    $('.water').click(function () {
        $('.fruit').css('color', 'blue')
        $('.checkAll').css('color', 'blue')
        $('.meat').css('color', 'blue')
        $('.water').css('color', 'red')
        $('.snake').css('color', 'blue')
        for (let i = 0; i < goodsType.length; i++) {
            if ($(this).text() == goodsType[i].innerText) {
                //console.log($(goodsType[i]))
                $(goodsType[i][i]).parent().siblings().css('display', 'none')
                $(goodsType[i]).parent().css('display', 'block')

            }
            else {
                $(goodsType[i]).parent().css('display', 'none')
            }
        }

    })

    //零食
    $('.snake').click(function () {
        $('.fruit').css('color', 'blue')
        $('.checkAll').css('color', 'blue')
        $('.meat').css('color', 'blue')
        $('.water').css('color', 'blue')
        $('.snake').css('color', 'red')
        let goodsType = document.querySelectorAll('.goodsType')
        for (let i = 0; i < goodsType.length; i++) {
            if ($(this).text() == goodsType[i].innerText) {
                //console.log($(goodsType[i]))
                $(goodsType[i][i]).parent().siblings().css('display', 'none')
                $(goodsType[i]).parent().css('display', 'block')
            }
            else {
                $(goodsType[i]).parent().css('display', 'none')
            }
        }

    })
    //奇数行、偶数行
    $('.firstTr:odd').css('background', '#ccc')
    $('.firstTr:even').css('background', 'pink')

</script>